package com.xx.library.controller;

import com.xx.library.common.Result;
import com.xx.library.dto.LoginRequest;
import com.xx.library.entity.User;
import com.xx.library.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public Result<User> getUserById(@PathVariable Long id) {
        return Result.success(userService.getUserById(id));
    }

    @GetMapping
    public Result<List<User>> getAllUsers() {
        return Result.success(userService.getAllUsers());
    }

    @GetMapping("/search")
    public Result<List<User>> searchUsers(User user) {
        return Result.success(userService.getUsersByCondition(user));
    }

    @PostMapping
    public Result<Void> addUser(@RequestBody User user) {
        userService.addUser(user);
        return Result.success();
    }

    @PutMapping
    public Result<Void> updateUser(@RequestBody User user) {
        userService.updateUser(user);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<Void> deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
        return Result.success();
    }

    @PostMapping("/login")
    public Result<User> login(@RequestBody LoginRequest loginRequest, HttpSession session) {
        User user = userService.login(loginRequest.getUsername(), loginRequest.getPassword());
        session.setAttribute("user", user);
        return Result.success(user);
    }

    @PostMapping("/register")
    public Result<Void> register(@RequestBody User user) {
        userService.register(user);
        return Result.success();
    }
} 